package org.example.questionnairebackend.controller;

import lombok.extern.slf4j.Slf4j;

import org.example.questionnairebackend.Data.Users;
import org.example.questionnairebackend.Dto.AddUser;
import org.example.questionnairebackend.Dto.LoginDto;
import org.example.questionnairebackend.properties.JwtProperties;
import org.example.questionnairebackend.result.Result;
import org.example.questionnairebackend.service.UserService;
import org.example.questionnairebackend.utils.JwtUtil;
import org.slf4j.MDC;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
@CrossOrigin(value = "*")
public class UserController {
    //登录方法
    @Autowired
    UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    public Result<Users> login(@RequestBody LoginDto dto) {
        log.info("用户登录{}", dto);
        MDC.put("userId", dto.getLoginname().toString());
        if (dto.getLoginname() == null || dto.getPassword() == null) {
            return Result.error("账号或密码不能为空");
        }
        Users user = userService.login(dto);
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        user.setToken(token);
        return Result.success(user);
    }

    //用户注册
    @PostMapping("/create")
    public Result register(@RequestBody AddUser user) {
        log.info("用户注册{}", user);
        if (user.getPassword() == null || user.getUsername() == null) {
            return Result.error("账号或密码不能为空");
        }
        Users user1 = new Users();
        BeanUtils.copyProperties(user, user1);
        userService.addUser(user1);
        return Result.success();
    }
    //删除用户
    @DeleteMapping("/deleteUser")
    public Result deleteUser(@RequestParam Long userId){
        log.info("删除用户：{}",userId);
        userService.deleteUser(userId);
        return Result.success();
    }
}
